//
//  QBSearchTVC.swift
//  QBCustomImageTag
//
//  Created by 乐启榜 on 16/8/25.
//  Copyright © 2016年 乐启榜. All rights reserved.
//

import UIKit

protocol QBSearchTVCDelegate: class {
    func didSelectedTitleString(title: String)
}

class QBSearchTVC: UITableViewController,UISearchBarDelegate {
    
    weak var delegate: QBSearchTVCDelegate?
    
    var text: String? = ""{
        didSet{
            searchBar.text = text
        }
    }
    
    private var dataSource: NSMutableArray!
    
    private lazy var searchBar: UISearchBar = {
        let _searchBar = UISearchBar()
            _searchBar.placeholder = "搜索商品"
            _searchBar.keyboardType = .Default
            _searchBar.delegate = self
        return _searchBar
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.titleView = searchBar
        
        
        let path = NSBundle.mainBundle().pathForResource("DataSource", ofType: "plist")
        if let _path = path {
            dataSource = NSMutableArray(contentsOfFile: _path)
        }else{
        }
        
        
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        if !(self.navigationController?.viewControllers.contains(self))!{
            searchBar.resignFirstResponder()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        guard let _dataSource = dataSource else {return 0}
        return _dataSource.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        guard let _arr = dataSource[section]["friends"] as? Array<String> else {
            print("数组转化失败")
            return 0
        }
        
        return _arr.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        
        if let _arr = dataSource[indexPath.section]["friends"] as? Array<String> {
        
             cell.textLabel?.text = _arr[indexPath.row]
            
        }

        return cell
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        guard let dataDic = dataSource[section] as? [String : NSObject] else{
            print("字典转化失败")
            return ""
        }
        
        guard let _group = dataDic["group"] else {
            print("获取group失败")
            return ""
        }
        
        return _group as? String

        
    }
    
    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40.0
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if let _arr = dataSource[indexPath.section]["friends"] as? Array<String> {
            
            delegate?.didSelectedTitleString(_arr[indexPath.row])
            self.navigationController?.popViewControllerAnimated(true)
            
        }
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
